package com.ruan.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.ruan.common.Code;
import com.ruan.common.Result;
import com.ruan.exception.BusinessException;
import com.ruan.exception.SystemException;
import com.ruan.mapper.*;
import com.ruan.pojo.*;
import com.ruan.service.EmployeeService;
import com.ruan.service.ResignService;
import com.ruan.utils.DateUtils;
import com.ruan.utils.SMSUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import javax.annotation.Resource;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;

@Service
@Transactional
@Slf4j
public class ResignServiceImpl extends ServiceImpl<ResignMapper, Resign> implements ResignService {

    @Resource
    private ResignMapper resignMapper;

    @Resource
    private EmployeeMapper employeeMapper;

    @Resource
    private EmployeeService employeeService;

    @Resource
    private EmployeeLeaveMapper employeeLeaveMapper;//请假

    @Resource
    private BusinessTripMapper businessTripMapper;//出差

    @Resource
    private OverTimeMapper overTimeMapper;//加班

    @Resource
    private OnDutyMapper onDutyMapper;//出勤

    @Resource
    private MonthCountMapper monthCountMapper;//月统计

    @Resource
    private AdminMapper adminMapper;

    @Resource
    private CommonUserMapper commonUserMapper;

    @Resource
    private DepartmentMapper departmentMapper;

    @Resource
    private SalaryMapper salaryMapper;

    @Resource
    private SalarySetMapper salarySetMapper;


    /**
     * 同意员工离职
     * @param id 员工ID
     * @param adminId 管理员ID
     */
    @Override
    public void agreeResign(Integer id,Integer adminId) {
        Resign resign = resignMapper.selectById(id);
        Admin admin = adminMapper.selectById(adminId);
        if (resign != null){
            Long employeeId = resign.getEmployeeId();//员工手机号
            Employee employee1 = employeeService.getById(employeeId);
            String phone = employee1.getPhone();//员工手机号
            resign.setStatus("通过");
            resign.setApprover(admin.getUsername());
            int rs = resignMapper.updateById(resign);
            if (rs > 0){

                LambdaQueryWrapper<CommonUser> commonUserWrapper = new LambdaQueryWrapper<>();

                commonUserWrapper.eq(CommonUser::getPhone,employee1.getPhone());
                CommonUser commonUser = commonUserMapper.selectOne(commonUserWrapper);
                if (commonUser != null){
                    commonUser.setStatus("禁用");
                    commonUserMapper.updateById(commonUser);//离职后禁用员工账号
                }else {

                    throw new SystemException(Code.BUSINESS_ERR,"此员工账号查找失败！");
                }

                LambdaQueryWrapper<Employee> employeeWrapper = new LambdaQueryWrapper();
                employeeWrapper.eq(Employee::getPhone,phone);
                Employee employee = employeeMapper.selectOne(employeeWrapper);
                if (employee!=null){
                    employee.setStatus("离职");//离职后设置员工状态为离职
                    employee.setApprover(admin.getUsername());//设置员工离职审批人
                    employee.setOuttime(new java.sql.Date(System.currentTimeMillis()));
                    employeeMapper.updateById(employee);

                    Long departId = employee.getDepartmentId();
                    Department department = departmentMapper.selectById(departId);
                    //不必写，查看部门时会自动查找
                    department.setNumber(department.getNumber()-1);//离职后对应部门人数-1
                    departmentMapper.updateById(department);

                }else {
                    throw new BusinessException(Code.SELECT_ERR,"查无此人");
                }

                LambdaQueryWrapper<EmployeeLeave> leaveWrapper = new LambdaQueryWrapper();
                LambdaQueryWrapper<BusinessTrip> tripWrapper = new LambdaQueryWrapper();
                LambdaQueryWrapper<OverTime> overTimeWrapper = new LambdaQueryWrapper();
                LambdaQueryWrapper<OnDuty> onDutyWrapper = new LambdaQueryWrapper();
                LambdaQueryWrapper<MonthCount> monthCountWrapper = new LambdaQueryWrapper();
                LambdaQueryWrapper<Salary> salaryWrapper = new LambdaQueryWrapper<>();
                LambdaQueryWrapper<SalarySet> salarySetWrapper = new LambdaQueryWrapper<>();

                //-----------------------------------

                leaveWrapper.eq(EmployeeLeave::getEmployeeId,employee1.getId());
                tripWrapper.eq(BusinessTrip::getEmployeeId,employee1.getId());
                overTimeWrapper.eq(OverTime::getEmployeeId,employee1.getId());
                onDutyWrapper.eq(OnDuty::getEmployeeId,employee1.getId());
                monthCountWrapper.eq(MonthCount::getEmployeeId,employee1.getId());
                salaryWrapper.eq(Salary::getEmployeeId,employee1.getId());
                salarySetWrapper.eq(SalarySet::getEmployeeId,employee1.getId());

                List<EmployeeLeave> employeeLeaveList = employeeLeaveMapper.selectList(leaveWrapper);
                if (employeeLeaveList.size()>0){
                    employeeLeaveMapper.delete(leaveWrapper);//离职后删除对应的请假记录
                }

                List<BusinessTrip> businessTripList = businessTripMapper.selectList(tripWrapper);
                if (businessTripList.size()>0){

                    businessTripMapper.delete(tripWrapper);//离职后删除对应的出差记录

                }

                List<OverTime> overTimeList = overTimeMapper.selectList(overTimeWrapper);
                if (overTimeList.size()>0){

                    overTimeMapper.delete(overTimeWrapper);//离职后删除对应的加班记录

                }

                List<OnDuty> onDuty = onDutyMapper.selectList(onDutyWrapper);
                if (onDuty.size()>0){

                    onDutyMapper.delete(onDutyWrapper);//离职后删除对应的出勤记录

                }

                List<MonthCount> monthCountList = monthCountMapper.selectList(monthCountWrapper);
                if (monthCountList.size()>0){
                    monthCountMapper.delete(monthCountWrapper);//离职后删除对应的月统计记录
                }

                List<Salary> salaryList = salaryMapper.selectList(salaryWrapper);
                if (salaryList.size()>0){
                    salaryMapper.delete(salaryWrapper);//离职后删除对应的薪资记录
                }

                List<SalarySet> salarySetList = salarySetMapper.selectList(salarySetWrapper);
                if (salarySetList.size()>0){
                    salarySetMapper.delete(salarySetWrapper);//离职后删除对应的薪资设置
                }
                //------------------------------------
                Long employeeId1 = resign.getEmployeeId();
                Employee employee2 = employeeService.getById(employeeId1);
                String name = employee2.getName();//员工姓名
                java.sql.Date time = resign.getTime();
                SimpleDateFormat sdf = new SimpleDateFormat("yyyy年MM月dd日");
                String resignTime = sdf.format(time);
                SMSUtils.sendResignSuccess(phone,name,resignTime);

            }else {
                throw new BusinessException(Code.SELECT_ERR,"审核失败！");
            }

        }else {
            throw new BusinessException(Code.SELECT_ERR,"查无此人");
        }

    }

    /**
     * 驳回员工离职申请
     * @param id 员工ID
     * @param adminId 管理员ID
     */
    @Override
    public void refuseResign(Integer id,Integer adminId) {
        Resign resign = resignMapper.selectById(id);
        Admin admin = adminMapper.selectById(adminId);
        if (resign != null){
            resign.setStatus("驳回");//驳回后设置员工离职表状态为驳回
            resign.setApprover(admin.getUsername());
            int rs = resignMapper.updateById(resign);
            if (rs <= 0){
                throw new BusinessException(Code.BUSINESS_ERR,"审核失败！");
            }
        }else {
            throw new BusinessException(Code.SELECT_ERR,"查无此人");
        }
    }

    /**
     * 通过手机号查询员工离职申请的状态
     * @param phone 手机号
     * @return
     */
    @Override
    public Result selectResignStatus(String phone) {
        LambdaQueryWrapper<Resign> queryWrapper = new LambdaQueryWrapper<>();
        LambdaQueryWrapper<Employee> queryWrapper1 = new LambdaQueryWrapper<>();
        queryWrapper1.eq(Employee::getPhone,phone);
        Employee employee = employeeMapper.selectOne(queryWrapper1);

        queryWrapper.eq(Resign::getEmployeeId,employee.getId());
        queryWrapper.eq(Resign::getStatus,"待审核");
        Resign resign = resignMapper.selectOne(queryWrapper);
        if (resign!=null){
            return new Result(Code.RESIGN_OK,"您已提交离职申请，是否撤销？");
        }
        return new Result(Code.RESIGN_ERR,"未提交离职申请！");
    }

    /**
     * 员工撤销离职申请
     * @param phone
     */
    @Override
    public void deleteResignByPhone(String phone) {
        LambdaQueryWrapper<Resign> queryWrapper = new LambdaQueryWrapper<>();
        //------------------------------------
        LambdaQueryWrapper<Employee> queryWrapper1 = new LambdaQueryWrapper<>();
        queryWrapper1.eq(Employee::getPhone,phone);
        Employee employee = employeeMapper.selectOne(queryWrapper1);
        queryWrapper.eq(Resign::getEmployeeId,employee.getId());
        queryWrapper.eq(Resign::getStatus,"待审核");
        Resign resign = resignMapper.selectOne(queryWrapper);
        if (resign!=null){
            resignMapper.deleteById(resign);
        }else {
            throw new BusinessException(Code.SELECT_OK,"查无此人，删除失败！");
        }

    }

    /**
     * 提交申请离职
     * @param resign
     */
    @Override
    public Result appForResign(Resign resign) {
        resign.setSubmitTime(new Date());
        java.sql.Date time = resign.getTime();
        Date submitTime = resign.getSubmitTime();
        //使用 DateUtils.judgeResignTime(submitTime, time)
        // 方法来判断是否已经过了指定的时间，
        // 如果 result 的值为 true，这表示当前时间已经过了指定的时间（即已经过了离职时间）。
        //如果 result 的值为 false，这表示当前时间还未过指定的时间（即还未到达离职时间）。
        Boolean result = DateUtils.judgeResignTime(submitTime, time);
        if (result){
            resign.setStatus("待审核");
            resignMapper.insert(resign);
            return new Result(Code.SAVE_OK,"提交成功，待审核！");
        }else {
            return new Result(Code.SAVE_ERR,"请提前七天申请离职！");
        }
    }
}
